package com.info.zhiduoduo.common.utils;

import org.apache.commons.io.IOUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.json.XML;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

/**
 * <p> 需要的依赖包：
 *   <pre>
 *                <dependency>
 *                   <groupId>dom4j</groupId>
 *                   <artifactId>dom4j</artifactId>
 *                   <version>1.6.1</version>
 *               </dependency>
 *
 *               <!-- https://mvnrepository.com/artifact/org.json/json -->
 *               <dependency>
 *                   <groupId>org.json</groupId>
 *                   <artifactId>json</artifactId>
 *                   <version>20160810</version>
 *               </dependency>
 *
 *                <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-io -->
 *                <dependency>
 *                    <groupId>org.apache.commons</groupId>
 *                    <artifactId>commons-io</artifactId>
 *                    <version>1.3.2</version>
 *                </dependency>
 *  </pre>
 *
 * @author bob
 * @time 2019-06-14 11:12
 */
public class XmlUtil {


    /**
     * xml 转 json
     * @param xmlReq String 类型的 xml
     * @return String 类型的 json
     */
    public static String xml2jsonString(String xmlReq) {
        String result = null;
        org.json.JSONObject xmlJSONObj ;
        try {
            byte[] b = xmlReq.getBytes();
            InputStream in = new ByteArrayInputStream(b);

            String xml = IOUtils.toString(in);
            xmlJSONObj = XML.toJSONObject(xml);
            result = xmlJSONObj.toString();
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 将int数值转换为占四个字节的byte数组，本方法适用于(高位在前，低位在后)的顺序。  和bytesToInt2（）配套使用
     */
    public static byte[] intToBytes2(int value)
    {
        byte[] src = new byte[4];
        src[0] = (byte) ((value>>24) & 0xFF);
        src[1] = (byte) ((value>>16)& 0xFF);
        src[2] = (byte) ((value>>8)&0xFF);
        src[3] = (byte) (value & 0xFF);
        return src;
    }

    /**
     * byte数组中取int数值，本方法适用于(低位在后，高位在前)的顺序。和intToBytes2（）配套使用
     */
    public static int bytesToInt2(byte[] src, int offset) {
        int value;
        value = (int) ( ((src[offset] & 0xFF)<<24)
                |((src[offset+1] & 0xFF)<<16)
                |((src[offset+2] & 0xFF)<<8)
                |(src[offset+3] & 0xFF));
        return value;
    }

    /**
     * 将xml转化为Map集合
     *
     * @param request
     * @return
     */
    public static Map<String, String> xmlToMap(HttpServletRequest request) {
        Map<String, String> map = new HashMap<String, String>();
        SAXReader reader = new SAXReader();
        InputStream ins = null;
        try {
            ins = request.getInputStream();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        Document doc = null;
        String s = "";
        try {
            doc = reader.read(ins);
        } catch (DocumentException e1) {
            e1.printStackTrace();
        }
        Element root = doc.getRootElement();
        @SuppressWarnings("unchecked") List<Element> list = root.elements();
        for (Element e : list) {
            map.put(e.getName(), e.getText());
        }
        try {
            ins.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return map;
    }

    /**
     * 将xml转化为Map集合
     *
     * @param xml
     * @return
     */
    public static Map<String, String> xmlToMap(String xml) {
        Map<String, String> map = new HashMap<String, String>();
        Document doc = null;
        try {
            doc = DocumentHelper.parseText(xml);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        Element root = doc.getRootElement();
        @SuppressWarnings("unchecked") List<Element> list = root.elements();
        for (Element e : list) {
            map.put(e.getName(), e.getText());
        }
        return map;
    }
}
